<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/2/002
 * Time: 11:48
 */

namespace App\Http\Controllers\Admin;


use App\Http\Common\Lib\Common;
use Illuminate\Http\Request;

class UploadController extends BaseAdminController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function image(){
        $image = \request()->file('image');
        $tag = \request()->input('tag','posts');
        if(!$tag){
            $tag = 'posts';
        }
        if(!$image){
            return response()->json(Common::dataFormat(config('statusInfo.status.noFile'),'缺少文件信息'));
        }
        if(!$image->isValid()){
            return response()->json(Common::dataFormat(config('statusInfo.status.noFile'),config('statusInfo.msg.noFile')));
        }
        $size = $image->getSize();
        $maxSize = 1024*1024*3;
        $ext = $image->extension();
        $exts = ['png','gif','jpg','jpeg'];
        if(!in_array($ext,$exts)){
            return response()->json(Common::dataFormat(config('statusInfo.status.fail'),'错误的文件类型'));
        }
        if($size > $maxSize){
            return response()->json(Common::dataFormat(config('statusInfo.status.noFile'),'上传文件不能超过3M'));
        }

        $savePath = 'public/images/'.$tag;
        $newPath = $image->store($savePath);
        if($newPath){
            //$url = \request()->getHost().'/storage/'.$newPath;
            $url = '/storage/'.$newPath;
            $url = str_replace('storage/public/','storage/',$url);
            return response()->json(Common::dataFormat(config('statusInfo.status.success'),config('statusInfo.msg.success'),['url'=>$url]));
        }else{
            return response()->json(Common::dataFormat(config('statusInfo.status.fail'),$image->getError()));
        }

    }

}